import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ActivatedRoute}  from "@angular/router";
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../bi.service';

@Component({
  selector: 'apes-annual-card-order',
  templateUrl: './annual-card-order.component.html',
  styleUrls: ['../door-tube-center-all.scss']
})
export class AnnualCardOrderComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    { hide: true, style: 'default', label: '查询', id: 'action_query', loading: false }
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = window.innerHeight - 490 + 'px';
  hind: string = 'none';

  timeList: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;                     // 默认结束时间
  startDate = null;                   // 默认开始时间 当天
  days: any;
  saleList:any [];
  sale = [];
  saleID: any[]

  sevenData: any[];    // 柱型图相关

  // 饼图相关
  salesPieData: any;
  xinbao = [];
  xubao = [];
  xin = 0;
  xu = 0;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData :any;
  companyList: any[];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private routerInfo: ActivatedRoute,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "门店名称", field: 'MDMC'},
      {headerName: "销售组", field: 'XSZMC'},
      {headerName: "年卡会员总数", field: 'NKHYZS'},
      {headerName: "年卡订单总数", field: 'NKDDZS'},
      {headerName: "新开卡数", field: 'XKKS'},
      {headerName: "续卡数", field: 'XKS'},
      {headerName: "年卡均价", field: 'NKJJ'},
      {headerName: "年卡总金额", field: 'NKZJE'},
      {headerName: "新增年卡转化率", field: 'XZNKZHL'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (0 * 24 * 60 * 60 * 1000));
    this.timeList.push(this.startDate);
    this.timeList.push(this.endDate);
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this.queryData();
    this.getSaleData();
  }

  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      }
    }
  }

  // 日期相减
  getTimeChang(d1, d2) {
    let day = 24 * 60 * 60 * 1000;
    try {
      let dateArr = d1.split('-');
      let checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      let checkTime = checkDate.getTime();

      let dateArr2 = d2.split('-');
      let checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      let checkTime2 = checkDate2.getTime();
      this.days = (checkTime - checkTime2) / day;
      if (this.days < 1) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }

  // 查询按钮事件
  queryData() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.xin = 0;
    this.xu = 0;
    this.xinbao = [];
    this.xubao = [];
    this.getDate(this.timeList, 'startValue', 'endValue');
    if (this.getTimeChang(this.endValue, this.startValue) === 'show') {
      this.hind = 'block';
    } else {
      // 判断日期不能为空
      if (this.startValue === null) {
        this.hind = 'block';
      }else{
        this.hind = 'none';
      }
    }
    //  必须满足以下条件才能调用接口
    if( this.hind === 'none'){
      this.getTablesData();
    }
    this.buttonBar[0].loading = false;
  }

  // 日期转换
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }


  getTablesData() {
    let data = { 'interfaceMethod': 'ipmMgzzForAppService.getNKDD', 'pdata': { 'XZRQ_SJ': this.endValue, 'XSZID': this.saleID, 'companyId': this.companyList } };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            for (let i = 0, len = data.length; i < len; i++) {
              data[i]['XZNKZHL'] = data[i]['XZNKZHL'] + '%';
            }
            this.rowData = data;
            if( this.rowData.length === 0 ) {
              this.msg.info(`未找到满足条件的数据`);
            }
            for (let i = 0, len = data.length; i < len; i++) {
              this.xinbao.push(data[i].XKKS);
              this.xubao.push(data[i].XKS);
            }
            // 饼图 新保数据获取
            for (let i = 0, len = this.xinbao.length; i < len; i++) {
              this.xin += this.xinbao[i];
            }
            // 饼图 续保数据获取
            for (let i = 0, len = this.xubao.length; i < len; i++) {
              this.xu += this.xubao[i];
            }
            //柱型图 数据获取
            const sevenList = data.slice(0, data.length);
            this.sevenData = sevenList.map((value) => {
              return { x: value['MDMC'], y: value['XB'] };
            });
            // 加载 饼图
            this.salesPieData = this.getSalesTypePie();
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取销售组
  getSaleData() {
    let data = {
      'interfaceMethod': 'ipmQueryXszService.queryXszData', 'pdata': { 'MJBJ': 0 },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.saleList = data;
            this.sale = this.saleList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 饼图
  getSalesTypePie() {
    return [
      { x: '新开卡', y: this.xin },
      { x: '续卡', y: this.xu },
    ];
  }

}
